package com.bodacn.storagescan;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.Socket;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmptyAgvActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG = this.getClass().getName();
    private final static int MSG_AllowScan=9000;
    private final static int MSG_ScanBarcodeOver=9001;
    private final static int MSG_ERROR =9002;
    private final static int MSG_AGVOK =9003;
    TextView txt_titleInv, tv_barcodeCaption,tv_ResultInfo;
    FrameLayout liner_title;
    Button btn_Query;
    ImageButton btn_return;
    EditText edit_Barcode;
    String serviceUrl="http://192.168.10.12/tvservice";
    String serviceUrlExt  = "/BDService.asmx?wsdl";
    String curLoginUserNo,curLoginUser,curLoginTime;//操作员所属部门等信息;
    String FormType="",Caption="",PrBarcode="",workShop="",PrPartName="";
    JSONArray detailJSON,progressJson;
    int pageItemCount=4;
    boolean ScanSign=false;
    //拦截扫描枪输入部分
    String BarcodeStr="";
    ScannerManager scannerManager;
    Socket updateSocket;
    EditText edit_placeNo;
    //全局变量
    private ProgressDialog waitDialog = null;
    ReentrantLock reentrantLock = new ReentrantLock();
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_emptyagv);
        InitView();
        //创建对话框，
        waitDialog=new ProgressDialog(this);
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curLoginTime=paramBundle.getString("LoginTime");
        serviceUrl=paramBundle.getString("serviceUrl");
        serviceUrlExt=paramBundle.getString("serviceUrlExt");
        FormType=paramBundle.getString("FormType");
        Caption=paramBundle.getString("Caption");
        //界面变量
        ((TextView)findViewById(R.id.tv_userName)).setText("用户:"+curLoginUser);
        //置标题颜色
        txt_titleInv.setText(Caption);
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code,String deviceName) {
                Log.d(TAG, "code= " + code);
                playRingtone();
                edit_Barcode.setText(code);
                ScanBarcode(edit_Barcode.getText().toString(),0);
            }
        },EmptyAgvActivity.this);
    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }


    //判断是否为数字，不然不转
    public static boolean isNumer(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    private void InitView(){
        edit_placeNo=findViewById(R.id.edit_placeNo);
        btn_Query=findViewById(R.id.btn_Scan);
        btn_Query.setOnClickListener(this);
        tv_ResultInfo=findViewById(R.id.tv_ResultInfo);
        edit_Barcode=findViewById(R.id.edit_Barcode);
        edit_Barcode.setInputType(InputType.TYPE_NULL);
        edit_Barcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edit_Barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_Barcode,InputMethodManager.SHOW_FORCED);
            }
        });
        edit_Barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    //Log.e("Debug","-----------------------------Debug-----------------------------");
                    //System.out.println(event);
                    if ((event.getAction()==KeyEvent.ACTION_UP)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        //System.out.println(edit_Barcode.getText().toString());
                        String barcode=edit_Barcode.getText().toString();
                        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                        Matcher m = p.matcher(barcode);
                        barcode = m.replaceAll("");
                        edit_Barcode.setText(barcode);
                        ScanBarcode(barcode,0);
                        ((TextView)findViewById(R.id.txt_PrBarcode)).setText(barcode);
                        return true;
                    }
                }
                return false;
            }
        });
        edit_Barcode.requestFocus();
        edit_Barcode.requestFocusFromTouch();
        liner_title=findViewById(R.id.liner_title);
        tv_barcodeCaption =findViewById(R.id.tv_barcodeCaption);
        txt_titleInv=findViewById(R.id.txt_titleInv);
        btn_return =findViewById(R.id.btn_return);
        btn_return.setOnClickListener(this);
        findViewById(R.id.btn_CallAGV).setOnClickListener(this);
        findViewById(R.id.btn_ClearPlace).setOnClickListener(this);

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View view) {
        hideIM(view);
        switch (view.getId()){
            case R.id.btn_return:
                finish();//关闭当前Activity，返回上一级;
                break;
            case R.id.btn_Scan:
                if ((edit_Barcode.getText()!=null)&&(edit_Barcode.getText().length()>0)) {
                    ScanBarcode(edit_Barcode.getText().toString(),0);
                } else Toast.makeText(getApplicationContext(),"请先输入条码!",Toast.LENGTH_LONG).show();
                break;

            case R.id.btn_CallAGV:
                if (edit_placeNo.getText().toString().length()>0){
                    sendDataAGV(edit_placeNo.getText().toString());
                } else {
                    Toast.makeText(this,"请扫描位置号！",Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_ClearPlace:
                if (edit_placeNo.getText().toString().length()>0){
                    sendDataClearPlace(edit_placeNo.getText().toString());
                } else {
                    Toast.makeText(this,"请扫描位置号！",Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }

    //发送数据给盛元成;string msg = string.Format("28,{0}" + "\r\n", PlaceNoEdit.Text);
    private void sendDataAGV(final String place) {
        System.out.println("呼叫AGV：place："+place);
        //线程调用过程;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String msg="";
                //将数据读到JSONArray;
                try {
                    updateSocket = new Socket("10.10.23.32", 6000);
                    DataOutputStream dout =new DataOutputStream(updateSocket.getOutputStream());
                    msg = String.format("28,%s\r\n", place);
                    System.out.println("msg:"+msg);
                    //发送数据
                    dout.writeBytes(msg);
                    dout.flush();
                    Thread.sleep(50, 0);
                } catch (Exception e){
                    System.out.println("sendDataAGV:"+e.getMessage());
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo",e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    handler.removeMessages(errmsg.what);
                    handler.sendMessage(errmsg);
                } finally {
                    //准备接收数据;
                    System.out.println("准备接收数据");
                    try {
                        DataInputStream din = new DataInputStream(updateSocket.getInputStream());
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        String JsonStr = null;
                        byte[] by = new byte[2048];
                        int n;
                        while ((n = din.read(by)) != -1)
                        {
                            baos.write(by, 0, n);
                        }
                        JsonStr = new String(baos.toByteArray(),"utf-8");
                        System.out.println("AGV返回:"+JsonStr);
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle=new Bundle();
                        String[] strings=JsonStr.split(",");
                        if (strings.length==0) {
                            bundle.putString("HintInfo", "未能正常响应！");
                            bundle.putString("msg", msg);
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            handler.removeMessages(errmsg.what);
                            handler.sendMessage(errmsg);
                            return;
                        }
                        if (strings[0].trim().equals("SUCCESS")) {
                            bundle.putString("HintInfo", JsonStr+":呼叫成功,等待AGV搬运!!");
                            bundle.putString("msg", msg);
                            errmsg.what = MSG_AGVOK;
                            errmsg.setData(bundle);
                        } else {
                            if (strings.length>1){
                                System.out.println("strings1-"+strings[1]);
                                if (strings[1].trim().equals("2")) {
                                    System.out.println("aaa");
                                    JsonStr="搬运目的地位置已满！";
                                }
                                if (strings[1].trim().equals("3")) JsonStr="当前位置已呼叫！";
                                if (strings[1].trim().equals("9")) JsonStr="AGV队列已满，呼叫取消！";
                            }
                            System.out.println("JsonStr:"+JsonStr);
                            bundle.putString("HintInfo", JsonStr);
                            bundle.putString("msg", msg);
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                        }
                        handler.removeMessages(errmsg.what);
                        handler.sendMessage(errmsg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        };
        new Thread(run).start();

    }

    //登陆校验;
    private void ScanBarcode(String paramBarcode,int inProgress){
        hideIM(edit_Barcode);
        if (ScanSign==false) {
            ScanSign=true;
            //组织WebService地址;
            edit_Barcode.setEnabled(false);
            edit_Barcode.setText("");
            String SqlComm = "Exec Assay_NAGV_CallA2 @Barcode='" + paramBarcode+"',@PrPlaceNo='" +((EditText) findViewById(R.id.edit_placeNo))+ "',@UserNo='" + curLoginUserNo + "'";
            PrBarcode = paramBarcode;
            //调用WebService过程并处理界面更新;
            ReadSQLData(SqlComm);
        } else Toast.makeText(this,"请稍等或退出重进!",Toast.LENGTH_LONG).show();
    }



    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            if (waitDialog.isShowing()) waitDialog.hide();
            int msgId = msg.what;
            hideIM(edit_Barcode);
            edit_Barcode.setEnabled(true);
            edit_Barcode.selectAll();
            edit_Barcode.requestFocus();
            ScanSign=false;
            Bundle bundle=msg.getData();
            switch (msgId) {
                case MSG_ScanBarcodeOver:
                    if (detailJSON != null) {
                        //填充屏幕
                        fillScreen(detailJSON.optJSONObject(0));
                    }
                    break;
                case MSG_AllowScan:
                    break;
                case MSG_ERROR:
                    if (bundle!=null) {
                        tv_ResultInfo.setText(bundle.getString("HintInfo"));
                        //mediaPlayer.start();
                        AlertDialog alertDialog = new AlertDialog.Builder(tv_ResultInfo.getContext())
                                .setTitle(getString(R.string.SystemHint)).setMessage(bundle.getString("HintInfo"))
                                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        hideIM(edit_Barcode);
                                        edit_Barcode.selectAll();
                                        edit_Barcode.requestFocus();
                                        return;
                                    }
                                }).create(); // 创建对话框
                        alertDialog.show(); // 显示对话框
                    }
                    break;
                case MSG_AGVOK:
                    if (bundle!=null){
                         ReadSQLData("Exec dbo.Assay_NAGV_CallReturn @EmpNo='" + curLoginUserNo
                                + "',@PlaceNo='" + ((EditText) findViewById(R.id.edit_placeNo)).getText().toString()
                                + "',@Memo='" + bundle.getString("msg") + "',@CallType='A2'");
                    }
                    tv_ResultInfo.setText(bundle.getString("HintInfo"));
                    break;
                default:
                    break;
            }
        }
    };


    //发送数据给盛元成;string msg = string.Format("28,{0}" + "\r\n", PlaceNoEdit.Text);
    private void sendDataClearPlace(final String place) {
        System.out.println("呼叫AGV：place："+place);
        //线程调用过程;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String msg="";
                //将数据读到JSONArray;
                try {
                    updateSocket = new Socket("10.10.23.32", 6000);
                    DataOutputStream dout =new DataOutputStream(updateSocket.getOutputStream());
                    msg = String.format("29,%s\r\n", place);
                    System.out.println("msg:"+msg);
                    //发送数据
                    dout.writeBytes(msg);
                    dout.flush();
                    Thread.sleep(50, 0);
                } catch (Exception e){
                    System.out.println("sendDataAGV:"+e.getMessage());
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo",e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    handler.removeMessages(errmsg.what);
                    handler.sendMessage(errmsg);
                } finally {
                    //准备接收数据;
                    System.out.println("准备接收数据");
                    try {
                        DataInputStream din = new DataInputStream(updateSocket.getInputStream());
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        String JsonStr = null;
                        byte[] by = new byte[2048];
                        int n;
                        while ((n = din.read(by)) != -1)
                        {
                            baos.write(by, 0, n);
                        }
                        JsonStr = new String(baos.toByteArray(),"utf-8");
                        System.out.println("AGV返回:"+JsonStr);
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle=new Bundle();
                        String[] strings=JsonStr.split(",");
                        if (strings.length==0) {
                            bundle.putString("HintInfo", "未能正常响应！");
                            bundle.putString("msg", msg);
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            handler.removeMessages(errmsg.what);
                            handler.sendMessage(errmsg);
                            return;
                        }
                        if (strings[0].trim().equals("SUCCESS")) {
                            bundle.putString("HintInfo", JsonStr+":清除位置号成功!!");
                            bundle.putString("msg", msg);
                            errmsg.what = MSG_AGVOK;
                            errmsg.setData(bundle);
                        } else {
                            if (strings.length>1){
                                System.out.println("strings1-"+strings[1]);
                                if (strings[1].trim().equals("1")) JsonStr = "提供工位条码错误，请重试！";
                                if (strings[1].trim().equals("2")) JsonStr = "设置占位清空异常，请重试！";
                                if (strings[1].trim().equals("3")) JsonStr = "占位被保护，不能清空！";
                            }
                            System.out.println("JsonStr:"+JsonStr);
                            bundle.putString("HintInfo", JsonStr);
                            bundle.putString("msg", msg);
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                        }
                        handler.removeMessages(errmsg.what);
                        handler.sendMessage(errmsg);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        };
        new Thread(run).start();

    }
    private void fillScreen(JSONObject optJSONObject) {
        if (optJSONObject!=null){
            try {
                if (optJSONObject.has("PlaceNo")) ((EditText) findViewById(R.id.edit_placeNo)).setText(optJSONObject.getString("PlaceNo"));
                if (optJSONObject.has("ResultInfo")) ((TextView) findViewById(R.id.tv_ResultInfo)).setText(optJSONObject.getString("ResultInfo"));
                if (optJSONObject.has("ErrInfo") == true) {
                    //MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(), R.raw.warn);
                    //mediaPlayer.start();
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle(getString(R.string.SystemHint)).setMessage(optJSONObject.getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideIM(edit_Barcode);
                                    edit_Barcode.selectAll();
                                    edit_Barcode.requestFocus();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        ScanSign=true;
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try{
                    reentrantLock.lock();
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    ScanSign=false;
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OperType")){
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("ScanBarcode")==true){
                                detailJSON=jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_ScanBarcodeOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                        }
                    } else{
                        Message msg = new Message();
                        msg.what = MSG_AllowScan;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //刷新界面;
                    ScanSign=false;
                    Message msg = new Message();
                    msg.what = MSG_AllowScan;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                    reentrantLock.unlock();
                }finally {
                    reentrantLock.unlock();
                }

            }

        };
        new Thread(run).start();

    }



}
